package com.fhz.a2102high6.test4

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * 时间:2023/9/13
 * @author Mr.Feng
 * 简述: TODO
 */
fun main() = runBlocking {

    val async = async {
        1 + 1
    }
    val await = async.await()

    println(await)

    var a = withContext(Dispatchers.IO) {
        //网络
        1+1
    }

    println(a)







}
suspend fun <T> Call<T>.await() : T {
    return  suspendCoroutine { continuation ->
        enqueue(object : Callback<T> {
            override fun onResponse(call: Call<T>, response: Response<T>) {
                val body = response.body()
                if(body != null){
                    continuation.resume(body)
                }else{
                    continuation.resumeWithException(java.lang.RuntimeException("null"))
                }
            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                continuation.resumeWithException(t)
            }
        } )

    }
}
